package com.quanyan.ic.task;

import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.jobclient.JobClient;
import com.github.ltsopensource.jobclient.domain.Response;
import com.quanyan.ic.constants.JobConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by zhuo.shi on 2017/6/2.
 */
//@Component
public class TimerTaskJob {

    private static Logger logger = LoggerFactory.getLogger(TimerTaskJob.class);

    @Autowired
    private JobClient jobClient;

    /**
     * 初始化定时器任务
     */
    public void initTask() {

        Job failedMsgCheckJob = new Job();
        failedMsgCheckJob.setTaskId(JobConstant.FAILED_MSG_CHECK_TASK_ID);
        failedMsgCheckJob.setTaskTrackerNodeGroup(JobConstant.NODE_GROUP_TRACKER);
        failedMsgCheckJob.setNeedFeedback(true);
        failedMsgCheckJob.setReplaceOnExist(true);        // 当任务队列中存在这个任务的时候，是否替换更新
        failedMsgCheckJob.setRepeatCount(-1);             // 无限循环
        failedMsgCheckJob.setRepeatInterval(60 * 1000L);  // 1分钟执行一次
        Response response = jobClient.submitJob(failedMsgCheckJob);
        logger.info("轮询[failed msg queue]定时任务，返回结果: {}, \nresponse={}", response.getMsg(), response);

    }

    /**
     * 提交一个定时任务，指定时间执行
     *
     * @param params      传递给业务执行类的参数
     * @param taskId      任务id
     * @param executeTime 执行时间点
     */
    public void submitTask(Map<String, String> params, String taskId, long executeTime, long repeatInterval) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        logger.warn("executeTime=" + sf.format(new Date(executeTime)) + ", repeatInterval=" + repeatInterval);
        Job job = new Job();
        job.setTaskId(taskId);
        job.setTaskTrackerNodeGroup(JobConstant.NODE_GROUP_TRACKER);
        job.setNeedFeedback(true);
        job.setReplaceOnExist(true);        // 当任务队列中存在这个任务的时候，是否替换更新
        job.setTriggerTime(executeTime);    //设置指定时间执行，在指定时间点触发
        if (params != null && params.size() > 0) {
            job.setExtParams(params);           //执行任务用到的参数
        }
        if (repeatInterval != 0) {
            job.setRepeatCount(-1); //无限循环
            job.setRepeatInterval(repeatInterval); //每间隔多久执行一次，单位秒
        }
        Response response = jobClient.submitJob(job);

        logger.warn("启动定时任务：" + ((response.getMsg() == null) ? "" : response.getMsg()) + taskId + ", 参数：" + params +
                ", 在" + sf.format(new Date(executeTime)) + "时执行！" + " 返回结果: " + response);
    }
}
